package handler

import (
	"cloud-disk/global/db"
	"cloud-disk/logic"
	"cloud-disk/model/request"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func UserFileListHandler(c *gin.Context) {
	// 返回用户列表
	identity := c.GetString("identity")
	req := request.FileList{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	fileList := logic.UserFileListLogic(identity, req)
	// let dir file status = 1
	for _, v := range *fileList {
		if v.Type == "dir" {
			v.Status = 1
		}
	}
	c.JSON(http.StatusOK, fileList)
}

func UserFileDeleteHandler(c *gin.Context) {
	req := request.UserFileDelete{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	err = logic.UserFileDeleteLogic(req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")
}

func UserFileMoveHandler(c *gin.Context) {
	req := request.UserFileMove{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	err = logic.UserFileMoveLogic(req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")
}

func UserFileRenameHandler(c *gin.Context) {
	req := request.UserFileRename{}
	err := c.BindJSON(&req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "parameter error",
		})
		return
	}
	err = logic.UserFileRenameLogic(req)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")

}

// FileDownloadHandler 应该是下载用户已有的文件
// 参数包括  userRepository的字段
// 然后连接到 repositoryPool的location和status
func FileDownloadHandler(c *gin.Context) {
	repositoryIdentity := c.Param("repositoryIdentity")
	type Result struct {
		Name     string
		Location string
	}
	res := Result{}
	err := db.DB().
		Select("ur.name, rp.location").
		Table("user_repository as ur").
		Joins("left join repository_pool as rp on ur.repository_identity=rp.identity").
		Where("ur.repository_identity=? and rp.status=1", repositoryIdentity).
		Scan(&res).
		Error
	// 是否执行错误
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	// 是否有找到该条记录
	if res.Location == "" {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"msg": "no such file or file unavailable",
		})
		return
	}
	// 返回文件
	c.Header("Content-Type", "application/octet-stream")
	c.Header("content-disposition", "filename="+res.Name)
	c.File(res.Location)
}
